package com.deng.mina.server;

import com.deng.mina.common.filter.MyFilter;
import com.deng.mina.common.protocol.ProtocolFactory;
import com.deng.mina.common.util.LogUtils;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSessionConfig;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @Project
 * @Module
 * @JDK_Vserion 1.8
 * @Author DengLibin
 * @Email dlb@smarthse.cn
 * @Desc 服务端
 * @since 2019/9/17 0017 14:16
 */
public class MinaServer {
    private int port = 7080;
    private IoAcceptor acceptor;
    private IoHandler handler;
    public MinaServer(){
            init();
    }

    private void init() {
        acceptor = new NioSocketAcceptor(8);
        handler = new ServerHandler();
        // 过滤器
        DefaultIoFilterChainBuilder filterChain = acceptor.getFilterChain();
     /*
        filterChain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(
                Charset.forName("UTF-8"), // 字符集
                LineDelimiter.WINDOWS.getValue(), // 编码器
                LineDelimiter.WINDOWS.getValue() // 解码器
        )));*/
        // 使用自定义编解码器
        filterChain.addLast("codec", new ProtocolCodecFilter(new ProtocolFactory(Charset.forName("UTF-8"))));
        filterChain.addFirst("myFilter", new MyFilter());
        IoSessionConfig sessionConfig = acceptor.getSessionConfig(); // session配置
        sessionConfig.setReadBufferSize(1024); // 缓冲区大小
        sessionConfig.setIdleTime(IdleStatus.BOTH_IDLE, 10); // 多少秒没数通信报告一次空闲

        acceptor.setHandler(handler); // 设置handler
    }

    /**
     * 启动
     * @throws IOException
     */
    public void start() throws IOException {
        acceptor.bind(new InetSocketAddress(port)); // 绑定端口
        LogUtils.info("服务器启动成功,port = "+ port);
    }
}
